package com.briup.jdbc;

import org.junit.Test;

import java.sql.*;

public class PrepareStatementTest {

    // 使用preparedStatement解决sql注入问题
    @Test
    public void testPrepareStatement(){
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try  {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://192.168.179.11:3306/briup","root","root");
            // 先定义sql语句的结构，使用？给数据占位
            String sql = "select count(*) from t_user where name = ? and password = ?";
            // 创建预编译语句的对象
            preparedStatement = conn.prepareStatement(sql);
            // 向语句对象中插入数据
//            var username = "admin";
//            var userpwd = "admin";
            // sql注入，第一种情况
//            var username = "admin";
//            var userpwd = "' or '1'='1";
            // sql注入，第二种情况
            var username = "' or '1'='1'; -- ";
            var userpwd = "aaa";
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,userpwd);
            // 执行
            resultSet = preparedStatement.executeQuery();
            resultSet.next();
            int count = resultSet.getInt(1);
            if(count==0){
                System.out.println("登陆失败");
            }else {
                System.out.println("登陆成功");
            }

        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (preparedStatement !=null){
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
